package com.example.demo.controller;

import com.example.demo.entity.StudentCourseProgress;
import com.example.demo.service.StudentCourseProgressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/courses")
public class StudentCourseProgressController {

    @Autowired
    private StudentCourseProgressService progressService;

    // GET /api/courses/{courseId}/progress?studentId={id} - 获取学生课程进度
    @GetMapping("/{courseId}/progress")
    public ResponseEntity<StudentCourseProgress> getCourseProgress(
            @PathVariable("courseId") String courseId,  // 保持String类型，与实体类一致
            @RequestParam("studentId") String studentId
    ) {
        // 移除类型转换，直接使用String参数调用Service
        return progressService.findProgress(courseId, studentId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // PUT /api/courses/{courseId}/progress?studentId={id} - 更新学生课程进度
    @PutMapping("/{courseId}/progress")
    public ResponseEntity<?> updateCourseProgress(
            @PathVariable("courseId") String courseId,
            @RequestParam("studentId") String studentId,
            @RequestBody StudentCourseProgress progress
    ) {
        try {
            // 直接使用String类型设置ID，与实体类保持一致
            progress.setStudentId(studentId);
            progress.setCourseId(courseId);  // 不再进行int转换

            progressService.updateProgress(progress);
            return ResponseEntity.ok("进度更新成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("进度更新失败: " + e.getMessage());
        }
    }

    // POST /api/courses/{courseId}/progress - 创建初始进度记录
    @PostMapping("/{courseId}/progress")
    public ResponseEntity<?> createProgress(
            @PathVariable("courseId") String courseId,
            @RequestParam("studentId") String studentId
    ) {
        try {
            // 校验参数非空
            if (studentId == null || studentId.trim().isEmpty() ||
                    courseId == null || courseId.trim().isEmpty()) {
                return ResponseEntity.badRequest().body("学生ID和课程ID不能为空");
            }

            // 直接传递String类型参数，无需转换
            StudentCourseProgress progress = progressService.createInitialProgress(
                    studentId,
                    courseId
            );
            return new ResponseEntity<>(progress, HttpStatus.CREATED);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}